package jnpf.fico.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.base.entity.VisualdevEntity;
import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.config.ConfigValueUtil;
import jnpf.engine.enums.FlowStatusEnum;
import jnpf.exception.DataException;
import jnpf.exception.WorkFlowException;
import jnpf.fico.entity.ZcBillEntity;
import jnpf.fico.entity.ZcBillItemEntity;
import jnpf.fico.model.bill.*;
import jnpf.fico.model.operate.ZcBillOperatePagination;
import jnpf.fico.service.ZcBillItemService;
import jnpf.fico.service.ZcBillOperateService;
import jnpf.fico.service.ZcBillService;
import jnpf.permission.entity.UserEntity;
import jnpf.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 账单信息
 *
 * @版本： V3.2.0
 * @版权： 智果云科技（https://www.jnpfsoft.com）
 * @作者： JNPF开发平台组
 * @日期： 2024-10-22
 */
@Slf4j
@RestController
@Api(tags = "账单信息", value = "账单信息")
@RequestMapping("/api/zcgl/fico/bill")
public class ZcBillController {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private ConfigValueUtil configValueUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private ZcBillService zcBillService;

    @Autowired
    private ZcBillItemService zcBillItemService;

    @Autowired
    private ZcBillOperateService operateService;


    /**
     * 列表
     *
     * @param zcBillPagination
     * @return
     */
    @ApiOperation("获取列表")
    @PostMapping("/getList")
    public ActionResult list(@RequestBody ZcBillPagination zcBillPagination) throws IOException {
        List<ZcBillEntity> list = zcBillService.getList(zcBillPagination);
        //处理id字段转名称，若无需转或者为空可删除

        List<ZcBillListVO> listVO = JsonUtil.getJsonToList(list, ZcBillListVO.class);
        for (ZcBillListVO zcBillVO : listVO) {
            zcBillVO.setPaymentType_name(zcBillVO.getPaymentType());

            zcBillVO.setPaymentBillNo_name(zcBillVO.getPaymentBillNo());

            zcBillVO.setReceiptAccount_name(zcBillVO.getReceiptAccount());

            zcBillVO.setPaymentBy_name(zcBillVO.getPaymentBy());

            zcBillVO.setPaymentAccount_name(zcBillVO.getPaymentAccount());

            zcBillVO.setReceiptDate_name(zcBillVO.getReceiptDate());

            zcBillVO.setPaymentCertificateFile_name(generaterSwapUtil.getFileNameInJson(zcBillVO.getPaymentCertificateFile()));

            //封装计费周期
            Date expenseStartDate = zcBillVO.getExpenseStartDate();
            Date expenseEndDate = zcBillVO.getExpenseEndDate();
            if(ObjectUtil.isNotNull(expenseStartDate)&&ObjectUtil.isNotNull(expenseEndDate)){
                zcBillVO.setExpenseCycleDate(DateUtil.dateToString(expenseStartDate, "yyyy-MM-dd")+"至"+DateUtil.dateToString(expenseEndDate, "yyyy-MM-dd"));
            }

            //子表数据转换
            List<ZcBillItemEntity> zcBillItemList = zcBillService.getZcBillItemList(zcBillVO.getId(), zcBillPagination);
            List<ZcBillItemModel> zcBillItemModelList = JsonUtil.getJsonToList(zcBillItemList, ZcBillItemModel.class);
            for (ZcBillItemModel zcBillItemModel : zcBillItemModelList) {
            }
            zcBillVO.setZcBillItemList(zcBillItemModelList);
        }

        PageListVO vo = new PageListVO();
        vo.setList(listVO);
        PaginationVO page = JsonUtil.getJsonToBean(zcBillPagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);

    }

    /**
     * 创建
     *
     * @param zcBillForm
     * @return
     */
    @PostMapping
    @Transactional
    @ApiOperation("创建")
    public ActionResult create(@RequestBody @Valid ZcBillForm zcBillForm) throws DataException {
        boolean b = zcBillService.checkForm(zcBillForm, 0);
        if (b) {
            return ActionResult.fail("单行输入不能重复");
        }
        String mainId = RandomUtil.uuId();

        UserInfo userInfo = userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        ZcBillEntity entity = JsonUtil.getJsonToBean(zcBillForm, ZcBillEntity.class);
        entity.setId(mainId);
        zcBillService.save(entity);
        if (CollUtil.isNotEmpty(zcBillForm.getBillItems()) ) {
            List<ZcBillItemEntity> ZcBillItemList = JsonUtil.getJsonToList(zcBillForm.getBillItems(), ZcBillItemEntity.class);
            for (ZcBillItemEntity entitys : ZcBillItemList) {
                entitys.setId(RandomUtil.uuId());
                entitys.setParentid(entity.getId());

                zcBillItemService.save(entitys);
            }
        }

        return ActionResult.success("创建成功");
    }


    /**
     * 信息
     *
     * @param id
     * @return
     */
    @ApiOperation("信息")
    @GetMapping("/{id}")
    public ActionResult<ZcBillInfoVO> info(@PathVariable("id") String id) {
        ZcBillEntity entity = zcBillService.getInfo(id);
        ZcBillInfoVO vo = JsonUtil.getJsonToBean(entity, ZcBillInfoVO.class);

        //子表
        List<ZcBillItemEntity> ZcBillItemList = zcBillService.getZcBillItemList(id);
        for (ZcBillItemEntity zcbillitemEntity : ZcBillItemList) {
        }
        vo.setZcBillItemList(JsonUtil.getJsonToList(ZcBillItemList, ZcBillItemModel.class));
        //副表
        return ActionResult.success(vo);
    }

    /**
     * 表单信息(详情页)
     *
     * @param id
     * @return
     */
    @ApiOperation("表单信息(详情页)")
    @GetMapping("/detail/{id}")
    public ActionResult<ZcBillInfoVO> detailInfo(@PathVariable("id") String id) {
        ZcBillEntity entity = zcBillService.getInfo(id);
        ZcBillInfoVO vo = JsonUtil.getJsonToBean(entity, ZcBillInfoVO.class);

        //子表数据转换
        List<ZcBillItemEntity> zcBillItemList = zcBillService.getZcBillItemList(id);
        List<ZcBillItemModel> zcBillItemModelList = JsonUtil.getJsonToList(zcBillItemList, ZcBillItemModel.class);
        for (ZcBillItemModel zcBillItemModel : zcBillItemModelList) {
        }
        vo.setZcBillItemList(zcBillItemModelList);

        //附表数据转换

        //添加到详情表单对象中
        vo.setPaymentType(vo.getPaymentType());

        vo.setPaymentBillNo(vo.getPaymentBillNo());

        vo.setReceiptAccount(vo.getReceiptAccount());

        vo.setPaymentBy(vo.getPaymentBy());

        vo.setPaymentAccount(vo.getPaymentAccount());

        vo.setReceiptDate(vo.getReceiptDate());

        vo.setPaymentCertificateFile(generaterSwapUtil.getFileNameInJson(vo.getPaymentCertificateFile()));


        return ActionResult.success(vo);
    }

//
//    /**
//     * 更新
//     *
//     * @param id
//     * @param zcBillForm
//     * @return
//     */
//    @PutMapping("/{id}")
//    @Transactional
//    @ApiOperation("更新")
//    public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid ZcBillForm zcBillForm) throws DataException {
//        boolean b = zcBillService.checkForm(zcBillForm, 1);
//        if (b) {
//            return ActionResult.fail("单行输入不能重复");
//        }
//        UserInfo userInfo = userProvider.get();
//        ZcBillEntity entity = zcBillService.getInfo(id);
//        if (entity != null) {
//            ZcBillEntity subentity = JsonUtil.getJsonToBean(zcBillForm, ZcBillEntity.class);
//            boolean b1 = zcBillService.updateById(subentity);
//            if (!b1) {
//                return ActionResult.fail("当前表单原数据已被调整，请重新进入该页面编辑并提交数据");
//            }
//
//            QueryWrapper<ZcBillItemEntity> ZcBillItemqueryWrapper = new QueryWrapper<>();
//            ZcBillItemqueryWrapper.lambda().eq(ZcBillItemEntity::getParentid, entity.getId());
//            zcBillItemService.remove(ZcBillItemqueryWrapper);
//            if (zcBillForm.getZcbillitemList() != null) {
//                List<ZcBillItemEntity> ZcBillItemList = JsonUtil.getJsonToList(zcBillForm.getZcbillitemList(), ZcBillItemEntity.class);
//                for (ZcBillItemEntity entitys : ZcBillItemList) {
//
//
//                    entitys.setId(RandomUtil.uuId());
//                    entitys.setParentid(entity.getId());
//                    zcBillItemService.save(entitys);
//                }
//            }
//            return ActionResult.success("更新成功");
//        } else {
//            return ActionResult.fail("更新失败，数据不存在");
//        }
//    }


    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ApiOperation("删除")
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id) {
        ZcBillEntity entity = zcBillService.getInfo(id);
        if (entity != null) {
            zcBillService.delete(entity);
            QueryWrapper<ZcBillItemEntity> queryWrapperZcBillItem = new QueryWrapper<>();
            queryWrapperZcBillItem.lambda().eq(ZcBillItemEntity::getParentid, entity.getId());

            zcBillItemService.remove(queryWrapperZcBillItem);

        }
        return ActionResult.success("删除成功");
    }

    @ApiOperation("账单核账")
    @PostMapping("/review")
    public ActionResult<?> reviewBill(@RequestBody List<String> ids){
        zcBillService.reviewBill(ids);
        return ActionResult.success("核账成功");
    }

    @ApiOperation("获取合同金额汇总")
    @GetMapping("/getSumMoney")
    public ActionResult getSumMoney(){
        ZcBillSumMoneyDTO zcBillSumMoneyDTO = zcBillService.getSumMoney();
        return ActionResult.success("获取成功",zcBillSumMoneyDTO);
    }

    @ApiOperation("获取账单详情")
    @GetMapping("/getBillInfo/{id}")
    public ActionResult getBillInfo(@PathVariable("id") String id){
        ZcBillInfoDTO zcBillInfoDTO = zcBillService.getBillInfo(id);
        return ActionResult.success("获取成功",zcBillInfoDTO);
    }

    @ApiOperation("账单操作列表集合")
    @PostMapping("/operation/list")
    public ActionResult<?> getBillReduceList(@RequestBody ZcBillOperatePagination reducePagination){
        return ActionResult.success(operateService.pageBillOperateList(reducePagination));
    }

    @GetMapping("/operation/detail/{id}")
    public ActionResult<?> getBillOperationDetail(@PathVariable("id") String id){
        return ActionResult.success(operateService.getBillOperateDetail(id));
    }

    @ApiOperation("账单价格变更审批通过执行")
    @PostMapping("/operate/action")
    public ActionResult<?> reduceBillAction(@RequestBody ZcBillReduceApprovalForm form) {
        operateService.operateBill(form.getId());
        return ActionResult.success();
    }

    @ApiOperation("账单变更")
    @PostMapping("/update")
    public ActionResult<?> billUpdate(@RequestBody ZcBillReduceApprovalForm form){
        zcBillService.updateBill(form.getTaskId());
        return ActionResult.success("操作成功");
    }




    /**
     * 更新
     *
     * @param id
     * @param upData
     * @return
     */
    @PutMapping("/{id}")
    @Transactional
    @ApiOperation("更新")
    public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid Map<String, Object> upData) throws DataException {
        ZcBillForm zcBillForm = JsonUtil.getJsonToBean(upData, ZcBillForm.class);
//        boolean b = zcAssetInfoService.checkForm(zcAssetInfoForm, 1);
//        if (b) {
//            return ActionResult.fail("单行输入不能重复");
//        }
        String visualId = "624930574271784645";
        VisualdevEntity visualdevEntity = generaterSwapUtil.getVisualEntity(visualId);
        UserInfo userInfo = userProvider.get();
        ZcBillEntity zcBillEntity = zcBillService.getInfo(id);
        if (zcBillEntity != null) {
            System.out.println(zcBillEntity+"测试");
            ZcBillEntity subentity = JsonUtil.getJsonToBean(zcBillEntity, ZcBillEntity.class);
            System.out.println(subentity+"测试1");
            boolean b1 = zcBillService.updateById(subentity);
            if (!b1) {
                return ActionResult.fail("当前表单原数据已被调整，请重新进入该页面编辑并提交数据");
            }
//            //子表数据
//            if (ObjectUtil.isNotEmpty(zcBillForm.getZcbillitemList())) {
//                QueryWrapper<ZcAssetWarrantEntity> queryWrapperZcAssetWarrant = new QueryWrapper<>();
//                queryWrapperZcAssetWarrant.lambda().eq(ZcAssetWarrantEntity::getAssetId, entity.getId());
//                ZcAssetWarrantEntity zc_asset_warrantOneEntity = zcAssetWarrantService.getOne(queryWrapperZcAssetWarrant);
//                ZcAssetWarrantEntity zc_asset_warrantentity = JsonUtil.getJsonToBean(zcAssetInfoForm.getZc_asset_warrant(), ZcAssetWarrantEntity.class);
//                zc_asset_warrantentity.setId(zc_asset_warrantOneEntity.getId());
//                zc_asset_warrantentity.setAssetId(entity.getId());
//                zcAssetWarrantService.updateById(zc_asset_warrantentity);
//            }
//

            if (FlowStatusEnum.submit.getMessage().equals(zcBillForm.getStatus())) {
                try {
                    System.out.println(subentity+"ceas1");
                    generaterSwapUtil.submitFlowTask(visualdevEntity, id, subentity, userInfo, zcBillForm.getCandidateList(), 1);
                } catch (WorkFlowException e) {
                    e.printStackTrace();
                }
                return ActionResult.success("提交成功，请耐心等待");
            }
            return ActionResult.success("更新成功");
        } else {
            return ActionResult.fail("更新失败，数据不存在");
        }
    }

}
